<template>
  <!-- <div class="X_Plot_content">
    <div style="position: relative">
      <div class="bottom_title">
        <div class="bottom_titlebiox">
          <div style="display: flex; color: black; margin-left: 10px">
            <div style="width: 100px"></div>
            <div style="width: 120px">海拔：{{ tudeobj.height }}米</div>
            <div style="width: 100px">层级：{{ tudeobj.zoomLevel }}层</div>

            <div v-if="isparse" style="margin-left: 20px">
              经纬度：{{ tudeobj.longitude }},
              {{ tudeobj.latitude }}
            </div>
            <div v-else style="margin-left: 20px">
              经纬度：{{ tudeobj.Parselongitude }},
              {{ tudeobj.Parselatitude }}
            </div>
          </div>
          <div @click="isparse = !isparse" style="
              cursor: pointer;
              color: #3370ff;
              margin-right: 20px;
              width: 50px;
            ">
            切换
          </div>
        </div>
      </div>
      <div class="X_Plot_bottom">
        <div style="position: relative">
          <img style="position: absolute; width: 100%; height: 109px; left: 0" src="@/assets/img/27/bottombg.png" />
          <div class="X_Plot_bottom_leftbtn">
            <div class="X_Plot_bottom_leftbtn_item" :class="btomindex === item ? 'btnactive' : ''"
              style="cursor: pointer" v-for="(item, index) in bottomTitlesed" :key="item"
              @click="rightbtn(item, index)">
              <div class="X_Plot_bottom_leftbtn_item_title">{{ item }}</div>
            </div>
          </div>
          <div class="X_Plot_bottom_leftbtn_item" :class="btomindex === item ? 'btnactive' : ''" style="
              cursor: pointer;
              width: 120px;
              position: absolute;
              right: 14px;
              top: 30px;
            " v-for="(item, index) in ['设置']" :key="item" @click="rightbtn(item, index)">
            <div class="X_Plot_bottom_leftbtn_item_title">{{ item }}</div>
          </div>
          <div @click="sendmsg"
            style="position: absolute; left: 50px; top: 20px; width: 150px; height: 80px; border: 1px solid red; color: #fff; text-align: center; line-height: 80px; font-size: 50px; cursor: pointer;user-select: none;">
            发送
          </div>
        </div>
      </div>
    </div>
  </div> -->
  <Eldialog class="mbbh-dialog" :dialogvis="dialogVisible" diawidth="950" diatitle="目标标绘" diaheight="height:700"
    dioid="modelDialogRef" @beforeClose="beforeCloseed">
    <template #dialogbody>
      <div class="eldialog_cont">
        <div class="eldialog_cont_left">
          <!--  -->
          <div style="
              margin-bottom: 16px;
              display: flex;
              justify-content: space-between;
              align-items: baseline;
            ">
            <div style="
                width: 270px;
                font-family: PingFangSC, PingFang SC;
                font-size: 14px;
                color: #c7f5f5;
              ">
              <span>目标编号：</span>
              <span>{{ form?.qian.KeyValue }}</span>
            </div>
            <el-button @click="startline" class="btnstyle">开始测绘</el-button>
          </div>
          <!--  -->
          <div class="checkoutbox">
            <div class="checkoutbox_item" v-for="(item, index) in position" :key="index"
              @click="clicheckout(item, 'position')">
              <!--  -->
              <div style="
                  width: 28px;
                  font-size: 14px;
                  font-family: PingFangSC, PingFang SC;
                ">
                {{ item.name }}
              </div>

              <img v-if="form.qian.ImageType == item.name" src="@/assets/img/27/aticdialog.png" />
              <img v-else width="12px" height="12px" src="@/assets/img/27/noaticdialog.png" />
            </div>

            <div class="checkoutbox_item" v-for="(item, index) in category" :key="index"
              @click="clicheckout(item, 'category')">
              <!--  -->
              <div style="
                  width: 28px;
                  font-size: 14px;
                  font-family: PingFangSC, PingFang SC;
                ">
                {{ item.name }}
              </div>

              <img v-if="form.qian.FriendOrFoe == item.name" src="@/assets/img/27/aticdialog.png" />
              <img v-else width="12px" height="12px" src="@/assets/img/27/noaticdialog.png" />
            </div>
          </div>

          <!--  -->
          <div style="display: flex; margin-bottom: 10px">
            <div style="width: 200px">目标位置</div>
          </div>
          <!--  -->

          <!--  -->
          <div class="">
            <div style="
                width: 450px;
                display: flex;
                align-items: center;
                justify-content: space-between;
              ">
              <span>经度：</span>
              <el-select popper-class="custom-dropdown" v-model="form.qian.jing.direction" style="width: 80px">
                <el-option label="E" value="E" />
                <el-option label="W" value="W" />
              </el-select>
              <el-input v-model.number="form.qian.jing.degrees" style="width: 100px" />
              <div class="dian"></div>
              <el-input v-model.number="form.qian.jing.minutes" style="width: 100px" />
              <div class="dian"></div>
              <el-input v-model.number="form.qian.jing.seconds" style="width: 100px" />
            </div>
            <div style="
                width: 450px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 20px;
              ">
              <span>维度：</span>
              <el-select popper-class="custom-dropdown" v-model="form.qian.wei.direction" style="width: 80px">
                <el-option label="N" value="N" />
                <el-option label="S" value="S" />
              </el-select>
              <el-input v-model.number="form.qian.wei.degrees" style="width: 100px" />
              <div class="dian"></div>
              <el-input v-model.number="form.qian.wei.minutes" style="width: 100px" />
              <div class="dian"></div>
              <el-input v-model.number="form.qian.wei.seconds" style="width: 100px" />
            </div>
            <!--  -->
            <div style="
                width: 450px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 20px;
              ">
              <div style="width: 232px">
                <span>高度：</span>
                <el-input-number style="width: 150px" v-model="form.qian.hei" controls-position="right" />
              </div>
              <div style="width: 220px; display: flex; align-items: center">
                <!-- <span>航向： </span>
                <el-input style="width: 276px" v-model="form.qian.Heading" /> -->
                <span>点时间： </span>
                <el-input style="width: 276px" v-model="form.qian.Heading" />
                <!-- type="datetime-local" -->
              </div>
            </div>
            <!--  -->
            <div style="
                width: 450px;
                display: flex;
                align-items: center;
                justify-content: flex-end;
                margin-top: 20px;
              ">


              <div style="width: 243px; display: flex; align-items: center">
                <el-button @click="finishDrawingPoints" class="btnstyle">
                  生成目标点
                </el-button>
                <el-button @click="targettion" class="btnstyle" style="width: 116px">
                  更改目标位置
                </el-button>
              </div>
            </div>
            <!--  -->
            <el-table ref="pointref" :data="tableData" height="220" highlight-current-row
              @current-change="handleCurrentChange" row-key="idid">
              <el-table-column prop="idid" label="点序" width="80" />
              <el-table-column prop="jing" label="经度" width="90" />
              <el-table-column prop="wei" label="纬度" width="90" />
              <el-table-column prop="time" label="点时间" />
            </el-table>
            <!--  -->
            <div style="
                width: 450px;
                margin-top: 20px;
                display: flex;
                justify-content: space-between;
              ">
              <el-button @click="switchToLineDrawing" class="btnstyle">生成目标</el-button>
              <el-button @click="removepoint" class="btnstyle"
                style="width: 148px; margin-right: 0">清除当前标绘信息</el-button>
            </div>
          </div>
        </div>
        <div class="eldialog_cont_right">
          <div style="
              margin-top: 20px;
              text-align: center;
              height: 20px;
              visibility: hidden;
            ">
            <!-- <el-button class="btnstyle">删除单点</el-button> -->
            <!-- <el-button class="btnstyle">删除全部</el-button> -->
          </div>
          <!--  -->
          <el-form :model="form" style="margin-top: 20px; padding-left: 20px; padding-right: 30px">
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">图层名称：</div>
              </template>
              <el-input v-model="form.qian.LayerName" style="width: 330px" />
            </el-form-item>
            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">敌我属性：</div>
              </template>
              <el-select @change="attchange" popper-class="custom-dropdown" style="width: 330px"
                v-model="form.qian.FriendOrFoe" placeholder="请选择">
                <el-option label="敌" value="敌" />
                <el-option label="我" value="我" />
                <el-option label="友" value="友" />
                <el-option label="中立" value="中立" />
                <el-option label="不明" value="不明" />
              </el-select>
            </el-form-item>
            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">类别：</div>
              </template>
              <el-select @change="attchange" popper-class="custom-dropdown" style="width: 330px"
                v-model="form.qian.ImageType" placeholder="请选择">
                <el-option label="水面" value="水面" />
                <el-option label="陆地" value="陆地" />
                <el-option label="空中" value="空中" />
                <el-option label="设施" value="设施" />
                <el-option label="空间" value="空间" />
              </el-select>
            </el-form-item>
            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">类型：</div>
              </template>
              <el-select popper-class="custom-dropdown" style="width: 330px" v-model="form.qian.IconType"
                placeholder="请选择">
                <el-option label="船" value="船" />
                <el-option label="飞机" value="飞机" />
              </el-select>
            </el-form-item>
            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">目标型号：</div>
              </template>
              <el-input v-model="form.qian.TargetType" style="width: 330px" />
            </el-form-item>

            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">目标名称：</div>
              </template>
              <el-input v-model="form.qian.TargetName" style="width: 330px" />
            </el-form-item>
            <!--  -->
            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">国家地区：</div>
              </template>
              <!-- <el-select popper-class="custom-dropdown" style="width: 330px" v-model="form.qian.TargetLocal">
                <el-option label="目标" value="目标" />
              </el-select> -->

              <el-input v-model="form.qian.TargetLocal" style="width: 330px" />

            </el-form-item>

            <el-form-item style="align-items: center">
              <template #label>
                <div style="color: #c7f5f5">属性颜色：</div>
              </template>
              <el-color-picker @active-change="changecolor" v-model="form.qian.LineColor" show-alpha />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </template>
  </Eldialog>
  <!--  -->
  <Eldialog :dialogvis="ismeteorology" diawidth="950" diatitle="气象列表" diaheight="height:902px" dioid="meteorologyRef"
    @beforeClose="beformeteorology">

    <template #dialogbody>
      <div style="margin-top: 20px">
        <div style="
            height: 40px;
            margin-top: 31px;
            margin-bottom: 20px;
            display: flex;
          ">
          <div style="display: flex; align-items: center">
            时间：
            <el-date-picker v-model="meteorolog.startTime" type="date" placeholder="请选择开始时间" value-format="YYYY-MM-DD"
              @change="getMeteorologicalapi()" prefix-icon="Calendar" style="width: 150px" />
            <div style="margin: 0 8px">-</div>
            <el-date-picker v-model="meteorolog.endTime" @change="getMeteorologicalapi()" type="date"
              placeholder="请选择结束时间" value-format="YYYY-MM-DD" prefix-icon="Calendar" style="width: 150px" />
          </div>
          <div style="display: flex; align-items: center; margin-left: 30px">
            粒度：
            <el-select v-model="meteorolog.dateMonth" popper-class="custom-dropdown" @change="getMeteorologicalapi()"
              style="width: 149px">
              <el-option label="天" value="天" />
              <el-option label="小时" value="小时" />

            </el-select>
          </div>
        </div>
        <el-table :data="meteorologdata" height="708" :header-cell-style="headerCellStyle">
          <el-table-column prop="sjgxsj" label="数据最后更新时间" width="200" />
          <el-table-column prop="n" label="云量" />
          <el-table-column prop="at" label="温度" />
          <el-table-column prop="dp03" label="降水量" />
          <el-table-column prop="pmspeed" label="风速" />

        </el-table>
        <el-pagination style="margin-top:10px;display: flex;justify-content: center;" :page-size="meteorolog.pageSize"
          layout="prev, pager, next" :total="totaldata" @current-change="ponhandleCurrentChange" />
      </div>
    </template>
  </Eldialog>
  <!--  -->
  <Eldialog :dialogvis="isbattledensity" diawidth="306" diatitle="兵力部署" diaheight="height:902px"
    dioid="battledensityRef" @beforeClose="beforebattledensity">
    <template #dialogbody>
      <el-tree v-if="treedata.length > 0" style="margin-top: 10px; overflow-x: hidden; height: 725px" :props="props"
        show-checkbox @check-change="treeclick" :data="treedata" node-key="id">
        <template #default="{ node, data }">
          <div style="width: 90%; display: flex;align-items: center;">
            <div style="margin-left: 8px;">{{ data.layerName }}</div>
          </div>
        </template>
      </el-tree>
    </template>
  </Eldialog>
  <!--  -->
  <!-- <Shzieldia v-model:dialogvis="isfit" diawidth="504" diatitle="设置" diaheight="height:430px" dioid="fitRef"
    @issheclose="beforefit" @isshecli="sheclibtn" /> -->

</template>

<script setup>
const sendmsg = async () => {
  // websocketStore.send('hello world')
  await postcs(
    [
      {
        "LayerName": "航线测试3333",
        "KeyValue": "001_123121112",
        "TrackLine": {
          "LineStyle": 1,
          "LineWidth": 3,
          "LineColor": {
            "R": 14,
            "G": 128,
            "B": 255,
            "A": 205
          }
        },
        "IsShowHeading": 0,
        "PointCount": 2,
        "Point": [
          {
            "Lon": 116.400000,
            "Lat": 39.900000,
            "Alt": 50
          },
          {
            "Lon": 116.500000,
            "Lat": 39.950000,
            "Alt": 80
          },
          {
            "Lon": 116.700000,
            "Lat": 39.950000,
            "Alt": 80
          },
          {
            "Lon": 116.500000,
            "Lat": 39.950000,
            "Alt": 80
          }
        ],
        "DesLength": 20,
        "DesValue": "飞机-J100"
      },
      {
        "LayerName": "航线测试33423",
        "KeyValue": "001_1244222221012",
        "TrackLine": {
          "LineStyle": 1,
          "LineWidth": 3,
          "LineColor": {
            "R": 14,
            "G": 128,
            "B": 255,
            "A": 205
          }
        },
        "IsShowHeading": 0,
        "PointCount": 2,
        "Point": [
          {
            "Lon": 109.0123000,
            "Lat": 39.9001230,
            "Alt": 50
          },
          {
            "Lon": 109.100000,
            "Lat": 39.950000,
            "Alt": 80
          },
          {
            "Lon": 116.722000,
            "Lat": 39.950000,
            "Alt": 80
          },
          {
            "Lon": 116.544000,
            "Lat": 39.950000,
            "Alt": 80
          }
        ],
        "DesLength": 20,
        "DesValue": "飞机-J110"
      }
    ]
  )
}

import {
  ref,
  onMounted,
  nextTick,
  onBeforeUnmount,
  getCurrentInstance,
  watch
} from "vue";
import Eldialog from "./components/eldialog.vue";
// import Shzieldia from "./components/shzieldia.vue";
const { proxy } = getCurrentInstance();
import { DrawTool } from "@/utils/cesiumExp-plot/src/index.js";
import { formatDMS, robustParseDMS, calculateHeading, Point3D, LineStyle, JIcon } from '@/utils/compnt'
import boatModel from "@/assets/glb/boat.glb";
import { getPlot, postAddPlot, putPlot, getDrawHeatMapTree, getMeteorological, postcs } from "@/api";
import { Heatmap3D } from "@/utils/HeatMap/cesiumHeatmap3D"

// 新增：导入TitleStore
import { useTitleStore } from '@/stores/TitleStore';
const titleStore = useTitleStore(); // 新增：创建titleStore实例

import { useWebSocketStore } from '@/stores/websocket';
const websocketStore = useWebSocketStore();
// 数据

const isparse = ref(true);

const dialogVisible = ref(false);

const pointref = ref()

const totaldata = ref()


const meteorolog = ref({
  startTime: proxy.$dayjs(new Date()).format("YYYY-MM-DD"),
  endTime: proxy.$dayjs(new Date()).format("YYYY-MM-DD"),
  dateMonth: '天',
  page: 1,
  pageSize: 16
})

const meteorologdata = ref([])

//
const position = ref([
  {
    name: "水面",
    ischek: true,
  },
  {
    name: "陆地",
    ischek: false,
  },
  {
    name: "空中",
    ischek: false,
  },
  {
    name: "设施",
    ischek: false,
  },
  {
    name: "空间",
    ischek: false,
  },
]);

const category = ref([
  {
    name: "敌",
    ischek: true,
    color: '#FF0002'
  },
  {
    name: "我",
    ischek: false,
    color: '#5C7BF9'
  },
  {
    name: "友",
    ischek: false,
    color: '#00DA6C'
  },
  {
    name: "中立",
    ischek: false,
    color: '#FF912E'
  },
  {
    name: "不明",
    ischek: false,
    color: '#FFFA15'
  },
]);

const btomindex = ref("");
// 新增：底部标题状态管理
const bottomTitlesed = ref([]);



const tableData = ref([]);

const editpointTools = ref(null);

const form = ref({
  hou: {
    LayerName: "",
    Icons: {},
    Heading: "",
    IsAddUnderLine: "",
    TargetPoints: [],
    FriendOrFoe: "",
    ImageType: "",
    IconType: "",
    TargetType: "",
    TargetName: "",
    TargetLocal: "",
    FileName: "",
    DesLength: "",
    DesValue: "",
  },
  qian: {

    jing: {
      direction: "",
      degrees: null,
      minutes: null,
      seconds: null,
    },
    wei: {
      direction: "",
      degrees: null,
      minutes: null,
      seconds: null,
    },
    hei: null,
    Heading: "",
    LineStyle: {},
    LayerName: '默认图层',
    FriendOrFoe: "敌", //敌我属性
    ImageType: "水面", //类别
    IconType: "", //类型
    TargetType: "", //目标型号
    TargetName: "", //目标名称
    TargetLocal: "", //国家地区
    LineColor: 'red',
  },
});

const ismeteorology = ref(false);

const headerCellStyle = ref({
  background: "rgb(27, 80, 132) !important",
  color: "#fff",
});
const isbattledensity = ref(false);

const treedata = ref([]);
const props = ref({
  children: "children",
  label: "layerName",
});

const isfit = ref(false);

const tudeobj = ref({});

//

// 方法
const rightbtn = (item, index) => {
  btomindex.value = item;
  switch (item) {
    case "目标标绘":
      dialogVisible.value = true;
      isponit.value = false
      nextTick(() => {
        // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
        const elDialog = document.getElementById("modelDialogRef");
        // @ts-ignore
        elDialog?.parentNode?.parentNode?.setAttribute(
          "style",
          "pointer-events: none;"
        );
      });
      break;
    case "气象数据":
      getMeteorologicalapi()
      ismeteorology.value = true;
      nextTick(() => {
        // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
        const elDialog = document.getElementById("meteorologyRef");
        // @ts-ignore
        elDialog?.parentNode?.parentNode?.setAttribute(
          "style",
          "pointer-events: none;"
        );
      });
      break;
    case "兵力部署热力图":
      isbattledensity.value = true;
      nextTick(() => {
        // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
        const elDialog = document.getElementById("battledensityRef");
        // @ts-ignore
        elDialog?.parentNode?.parentNode?.setAttribute(
          "style",
          "pointer-events: none;"
        );
      });
      break;
    case "设置":
      isfit.value = true;
      nextTick(() => {
        // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
        const elDialog = document.getElementById("fitRef");
        // @ts-ignore
        elDialog?.parentNode?.parentNode?.setAttribute(
          "style",
          "pointer-events: none;"
        );
      });
      break;
  }
};

const beforeCloseed = (data) => {

  if (data === "关闭") {
    removepoint()
    dialogVisible.value = false;
    editpointTools.value.endEdit();
    btomindex.value = null;
    form.value.qian = {
      jing: {
        direction: "",
        degrees: null,
        minutes: null,
        seconds: null,
      },
      wei: {
        direction: "",
        degrees: null,
        minutes: null,
        seconds: null,
      },
      hei: null,
      Heading: "",
      LineStyle: {},
      LayerName: '默认图层',
      FriendOrFoe: "敌", //敌我属性
      ImageType: "水面", //类别
      IconType: "", //类型
      TargetType: "", //目标型号
      TargetName: "", //目标名称
      TargetLocal: "", //国家地区
      LineColor: 'red'
    }
    getPlotapi();
  } else {
    dialogVisible.value = false;
  }
};

const clicheckout = (data, type) => {
  console.log('data', data);
  console.log('type', type);
  // 根据类型处理不同数组的单选逻辑
  if (type === "position") {
    // 取消同数组中其他项的选中状态
    position.value.forEach((item) => {
      item.ischek = item === data;
    });

    // 同步更新类别表单值
    form.value.qian.ImageType = data.name;
  } else if (type === "category") {
    // 取消同数组中其他项的选中状态
    category.value.forEach((item) => {
      item.ischek = item === data;
    });

    // 同步更新敌我属性表单值
    form.value.qian.FriendOrFoe = data.name;
    form.value.qian.LineColor = data.color
  }
};

const beformeteorology = (data) => {
  if (data === "关闭") {
    ismeteorology.value = false;
  } else {
    ismeteorology.value = false;
  }
};

const beforebattledensity = (data) => {
  if (data === "关闭") {
    isbattledensity.value = false;
  } else {
    isbattledensity.value = false;
  }
};

let ishame = null

const treeclick = (node, ische) => {
  if (ische) {
    ishame = new Heatmap3D(window.viewer, {
      geojson: node.heatmap,
      radius: 20,
      baseElevation: 0,
      colorGradient: {
        ".1": "blue",
        ".5": "yellow",
        ".7": "red",
        ".99": "white"
      }
    });
  } else {
    if (ishame !== null) {
      ishame.destroy()
    }
    ishame = null
  }
};

const beforefit = () => {
  isfit.value = false;
};

const sheclibtn = () => {
  isfit.value = false;
};
//

const arrrr = [];
const isponit = ref(false);
const entityData = ref(null);
const pointTools = ref(null);

const startline = () => {
  let pointData = {
    name: "点",
    type: "point",
    // iconImg: "./easy3d/images/plot/point.png",
    styleType: "point",
    show: false,
  };

  let polylineTool = new DrawTool(window.viewer, {
    canEdit: false,
  });

  pointTools.value = polylineTool;
  polylineTool.start(pointData);
  polylineTool.on("endCreate", (entityObj, entity) => {

    // 收集坐标并转换为经纬度


    entityData.value = entityObj;

    let arr = [];
    const positions = entityObj.getPositions();
    //
    const cartographic = Cesium.Cartographic.fromCartesian(positions);

    const longitude = Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = Cesium.Math.toDegrees(cartographic.latitude);
    //

    form.value.qian.jing = formatDMS(longitude, 6, false);
    form.value.qian.wei = formatDMS(latitude, 6, true);
    form.value.qian.hei = cartographic.height;
    arr.push(positions);
    if (arr && arr.length > 0) {
      // 遍历坐标并添加到表格
      arr.forEach((pos, index) => {
        const cartographic = Cesium.Cartographic.fromCartesian(pos);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        tableData.value.push({
          idid: tableData.value.length + 1,
          jing: longitude.toFixed(6),
          wei: latitude.toFixed(6),
          time: new Date().toLocaleString(),
          hei: cartographic.height.toFixed(6),
        });
      });
    }
  });
};

const finishDrawingPoints = () => {
  entityData.value.setVisible(true);
  arrrr.push({ attr: entityData.value.attr, entityData: entityData.value });

  if (tableData.value.length >= 2) {

    const positions = tableData.value.map((item) => {
      const longitude = parseFloat(item.jing);
      const latitude = parseFloat(item.wei);
      return Cesium.Cartesian3.fromDegrees(longitude, latitude);
    });


    const fromPos = positions[positions.length - 2];
    const toPos = positions[positions.length - 1];
    const heading = calculateHeading(fromPos, toPos);
    form.value.qian.Heading = heading.toFixed(2); // 更新航向表单值

  }


};

const switchToLineDrawing = () => {
  if (tableData.value.length < 2) {
    alert("至少需要2个点才能绘制线");
    return;
  }

  // 将表格中的点数据转换为Cesium坐标
  const positions = tableData.value.map((item) => {
    const longitude = parseFloat(item.jing);
    const latitude = parseFloat(item.wei);
    return Cesium.Cartesian3.fromDegrees(longitude, latitude);
  });
  // 初始化线绘制工具
  let polylineTool = new DrawTool(window.viewer, {
    canEdit: true,
  });
  pointTools.value = polylineTool;
  if (!polylineTool) return;
  editpointTools.value = polylineTool;
  // 使用已有点数据创建线
  polylineTool.createByPositions({
    type: "polyline",
    positions: positions,
    style: {
      color: form.value.qian.LineColor,
      width: 3,
    },
    model: boatModelid.value || '',

    success: async (entityObj, entity) => {
      if (!isponit.value) {
        entityData.value = entityObj;
      }

      arrrr.forEach((e) => {
        e.entityData.destroy()
      })



      arrrr.push({ attr: entityObj.attr, entityData: entityObj });

      console.log("线绘制完成", entityObj);
      // 添加模型实体 - 替换最后一个点
      if (positions.length > 0) {
        // 获取最后一个点的坐标
        const lastPosition = positions[positions.length - 1];

        // 创建模型实体
        if (isponit.value) {
          window.viewer.entities.values.forEach((e) => {
            if (e.name == entityObj.attr.model) {
              e.position.setValue(lastPosition)
            }
          });

        } else {
          window.viewer.entities.add({
            name: "boatModel_" + Number(new Date()),
            position: lastPosition,
            model: {
              uri: boatModel,
              scale: 1.0, // 根据需要调整模型大小
              minimumPixelSize: 64,
            },
          });

        }


        ///数据替换
        const linestyle = entityObj.getStyle()
        form.value.hou.LayerName = form.value.qian.LayerName
        form.value.hou.Heading = Number(form.value.qian.Heading) * 100
        form.value.hou.FriendOrFoe = form.value.qian.FriendOrFoe
        form.value.hou.ImageType = form.value.qian.ImageType
        form.value.hou.IconType = form.value.qian.IconType
        form.value.hou.TargetType = form.value.qian.TargetType
        form.value.hou.TargetName = form.value.qian.TargetName
        form.value.hou.TargetLocal = form.value.qian.TargetLocal
        form.value.hou.TargetPoints = tableData.value.map((e) => {
          return {
            Lat: Number(e.wei),
            Lon: Number(e.jing),
            Alt: Number(e.hei),
          }
        })
        form.value.hou.Icons = JIcon(linestyle, "", '1')
        if (isponit.value) {
          console.log('entityData.value', entityObj)
          form.value.hou.KeyValue = entityObj?.attr
            .model.modelid.KeyValue || entityObj.model.modelid.KeyValue
          // putPlot()
          await putPlot(form.value.hou)


        } else {
          form.value.hou.LayerNumber = 1
          await postAddPlot(form.value.hou)

        }

        beforeCloseed('关闭')
      }


    },
  });

  console.log("已使用点数据创建线");
  proxy.$mitt.emit("getsubmit")
};




const targettion = () => {
  let jing = "";
  let wei = "";
  let hei = form.value.qian.hei;

  jing = robustParseDMS(
    `${form.value.qian.jing.degrees}°${form.value.qian.jing.minutes}′${form.value.qian.jing.seconds}″${form.value.qian.jing.direction}`
  );
  wei = robustParseDMS(
    `${form.value.qian.wei.degrees}°${form.value.qian.wei.minutes}′${form.value.qian.wei.seconds}″${form.value.qian.wei.direction}`
  );


  const newPosition = Cesium.Cartesian3.fromDegrees(jing, wei, hei);

  entityData.value.position = newPosition;

  if (!isponit.value) {
    entityData.value.entity.position.setValue(newPosition);
  } else {
    let Pointarr = [];
    tableData.value.forEach((ele) => {
      if (showtable.value?.idid == ele.idid) {
        const newPosition = Cesium.Cartesian3.fromDegrees(jing, wei, hei);
        Pointarr.push(newPosition)
      } else {
        Pointarr.push(
          Cesium.Cartesian3.fromDegrees(
            Number(ele.jing),
            Number(ele.wei),
            Number(ele.hei)
          ));
      }
    });
    entityData.value.positions = Pointarr;
    updateControlPoints(entityData.value, Pointarr);
    window.viewer.entities.values.forEach((e) => {
      if (e.name == entityData.value.attr.model) {
        e.position.setValue(Pointarr[Pointarr.length - 1])
      }
    });
  }

  console.log(tableData.value, showtable.value)

  tableData.value.forEach((e) => {
    if (showtable.value?.idid == e.idid) {
      e.jing = jing;
      e.wei = wei;
    }
  });
}

const showtable = ref({});

const handleCurrentChange = (val) => {
  if (!dialogVisible.value) return
  showtable.value = val;
  form.value.qian.jing = formatDMS(Number(val.jing), 6, false);
  form.value.qian.wei = formatDMS(Number(val.wei), 6, true);
  form.value.qian.hei = Number(val.hei);
};

const attchange = (data) => {

  // 根据表单值更新asdasd数组（敌我属性）选中状态
  category.value.forEach((item) => {
    item.ischek = item.name === form.value.qian.FriendOrFoe;
    if (item.name == data) {
      form.value.qian.LineColor = item.color
    }
  });
  // // 根据表单值更新ceshi数组（类别）选中状态
  position.value.forEach((item) => {
    item.ischek = item.name === form.value.qian.ImageType;
  });
};

const removepoint = () => {
  arrrr.forEach((e) => {
    e.entityData.destroy();
  });
  if (isponit.value) {
    window.viewer.entities.values.forEach((e) => {
      if (e.name == boatModelid.value.model) {
        window.viewer.entities.remove(e); // 移除名称为 "boatModel" 的实体数据
      }
    });
  }
  tableData.value = [];
};

const boatModelid = ref()
//
const getPlotapi = async () => {
  const { data } = await getPlot()

  let polylineTool = new DrawTool(window.viewer, { canEdit: true });
  const objarr = polylineTool.createByGeojson(data, "boatModel_" + Number(new Date()))

  proxy.$mitt.on("Layerdata", ((e) => {
    console.log(e)
    polylineTool.getEntityObjArr().forEach((obj) => {
      if (obj.attr.formdata.KeyValue == e.KeyValue) {
        polylineTool.zoomToByObjId(obj.objId)
        form.value.qian.LayerName = e.LayerName
        form.value.qian.KeyValue = e.KeyValue
        polylineTool.startEditOne(obj)
      }
    })
  }));

  if (objarr.length > 0) {
    objarr.forEach((e, i) => {
      // 获取最后一个点的坐标
      const lastPosition = e.positions[e.positions.length - 1];
      // 创建模型实体
      window.viewer.entities.add({
        name: e.attr.model,
        position: lastPosition,
        model: {
          uri: boatModel,
          scale: 1.0, // 根据需要调整模型大小
          minimumPixelSize: 64,
        },
      });

    })
  }


  proxy.$mitt.on('checkedNodesmu', (checkedNodes) => {
    handleEntityVisibility(polylineTool, checkedNodes, '目标消息');
  })


  proxy.$mitt.on('checkedNodesChangedddd', (checkedNodes) => {
    handleEntityVisibility(polylineTool, checkedNodes);
  })




  polylineTool.getEntityObjArr().forEach((obj) => {
    obj.entity.show = false
    window.viewer.entities.values.forEach((items) => {
      if (items.name == obj.attr.model) {
        // console.log('items.name', items.name, obj.attr.model, items)
        items.show = false
      }
    })
  })



  editstatus(polylineTool)
}



const editstatus = (pointDrawTool,) => {

  pointDrawTool.on("editing", (entityObj, entity) => {
    console.log("正在编辑");
    entityData.value = entityObj;
  });

  pointDrawTool.on("endEdit", (entityObj, entity) => {
    console.log("结束编辑");


  });
  pointDrawTool.on("startEdit", (entityObj, entity) => {
    console.log("开始编辑", entityObj, entityObj.attr.model);
    entityData.value = entityObj;
    editpointTools.value = pointDrawTool;
    isponit.value = true
    boatModelid.value = { model: entityObj.attr.model, modelid: entityData.value.attr.formdata }
    drawPolylinefrom(entityObj, form.value)
  });

};

const handleEntityVisibility = (pointDrawTool, checkedNodes, type) => {
  if (!window.viewer || !window.viewer.entities) return;

  if (type == '目标消息') {
    // 遍历所有实体，根据选中状态设置显示/隐藏
    pointDrawTool.getEntityObjArr().forEach((obj) => {
      // 检查当前实体是否在选中节点中
      const isChecked = checkedNodes.some(item => obj.attr.formdata.KeyValue === item.KeyValue);

      // 修改这里：使用 setVisible 方法
      obj.setVisible(isChecked);
      window.viewer.entities.values.forEach((items) => {
        if (items.name == obj.attr.model) {
          items.show = isChecked
        }
      })
    });
  } else {
    // 遍历所有实体，根据选中状态设置显示/隐藏
    pointDrawTool.getEntityObjArr().forEach((obj) => {
      // 获取实体的 FriendOrFoe 和 ImageType 属性
      const friendOrFoe = obj.attr?.formdata?.FriendOrFoe;
      const imageType = obj.attr?.formdata?.ImageType;

      // 默认隐藏
      let isVisible = false;

      // 检查 friendOrFoe 是否在 checkedNodes.fa 中
      const isFriendOrFoeVisible = checkedNodes.fa.includes(imageType);

      // 检查 imageType 是否在 checkedNodes.che 中（过滤掉有 Children 的项）
      const isImageTypeVisible = checkedNodes.che
        .filter(item => !item.Children) // 过滤掉有 Children 属性的数据
        .some(item => item.LayerName === friendOrFoe);

      // 仅当两个条件都为 true 时，实体才显示
      isVisible = isFriendOrFoeVisible && isImageTypeVisible;

      // 修改这里：使用 setVisible 方法
      obj.setVisible(isVisible);
      //
      window.viewer.entities.values.forEach((items) => {
        if (items.name == obj.attr.model) {
          items.show = isVisible
        }
      })
    });
  }
};




const drawPolylinefrom = (entityObj, from) => {

  let poarr = [];
  entityObj.getPositions(true).forEach((e, i) => {
    poarr.push(
      {
        idid: i + 1,
        jing: Point3D(e).Lon.toFixed(6),
        wei: Point3D(e).Lat.toFixed(6),
        hei: Point3D(e).Alt.toFixed(6),
        time: new Date().toLocaleString()
      }

    );
  });
  tableData.value = poarr;

  console.log(from, entityObj)
  from.qian.TargetName = entityObj.attr.formdata.TargetName
  from.qian.IconType = entityObj.attr.formdata.IconType
  from.qian.FriendOrFoe = entityObj.attr.formdata.FriendOrFoe
  from.qian.ImageType = entityObj.attr.formdata.ImageType
  from.qian.TargetType = entityObj.attr.formdata.TargetType
  from.qian.LayerName = entityObj.attr.formdata.LayerName
  from.qian.TargetLocal = entityObj.attr.formdata.TargetLocal
  from.qian.Heading = entityObj.attr.formdata.Heading
  from.qian.KeyValue = entityObj.attr.formdata.KeyValue
  from.qian.LineColor = entityObj.attr.formdata.Icon.IconColor


  // category.value.forEach((e) => {
  //   if (from.qian.FriendOrFoe == e.name) {
  //     e.ischek = true
  //   }
  // })



  // from.qian.jing = formatDMS(tableData.value[0].jing, 6, true)
  // from.qian.wei = formatDMS(tableData.value[0].wei, 6, true)
  // from.qian.hei = tableData.value[0].hei

  //
  dialogVisible.value = true;
  nextTick(() => {
    // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
    const elDialog = document.getElementById("modelDialogRef");
    // @ts-ignore
    elDialog?.parentNode?.parentNode?.setAttribute(
      "style",
      "pointer-events: none;"
    );
    // pointref.value.setCurrentRow(tableData.value[0])
    showtable.value = tableData.value[0]
  });

};



const updateControlPoints = (polylineObj, newPositions) => {

  if (!polylineObj.controlPoints || polylineObj.controlPoints.length === 0)
    return;

  // 确保控制点数量与新坐标数量一致
  const pointCount = Math.min(
    polylineObj.controlPoints.length,
    newPositions.length
  );
  for (let i = 0; i < pointCount; i++) {
    const controlPoint = polylineObj.controlPoints[i];
    const newPosition = newPositions[i];
    console.log("controlPoint", controlPoint);
    console.log("newPosition", newPosition);
    // 更新控制点的位置
    if (controlPoint.point) {
      controlPoint.position.setValue(newPosition);
    }

    // 记录新位置索引
    controlPoint.wz = i;
  }

  // 处理多余的控制点（如果有）
  if (polylineObj.controlPoints.length > newPositions.length) {
    for (
      let i = newPositions.length;
      i < polylineObj.controlPoints.length;
      i++
    ) {
      polylineObj.viewer.entities.remove(polylineObj.controlPoints[i]);
    }
    polylineObj.controlPoints = polylineObj.controlPoints.slice(
      0,
      newPositions.length
    );
  }
};



const changecolor = (color) => {
  form.value.qian.LineColor = color
}

const getDrawHeatMapapi = async () => {
  const { data } = await getDrawHeatMapTree();
  treedata.value = data;
};

//
const getMeteorologicalapi = async () => {
  const { data } = await getMeteorological(meteorolog.value)
  meteorologdata.value = data.result
  totaldata.value = data.total
}

const ponhandleCurrentChange = (data) => {

  meteorolog.value.page = data

  getMeteorologicalapi()
}

//

const getSettingapi = async () => {
  // 从store获取数据
  await titleStore.fetchTitles();
  bottomTitlesed.value = titleStore.bottomTitles;
}


// 生命周期钩子
onMounted(() => {
  window.addEventListener('mbbh', (e) => {
    // console.log('e', e.detail.name)
    rightbtn(e.detail.name)
  });
  getDrawHeatMapapi()

  // 初始化操作
  proxy.$mitt.on("tude", (data) => {
    tudeobj.value = data;
  });
  nextTick(() => {
    proxy.$mitt.on("cesiumInitialized", (e) => {
      getPlotapi()
    });
  });

  // 从store初始化底部标题
  getSettingapi();

  // 添加对 titleStore.bottomTitles 变化的监听
  watch(
    () => titleStore.bottomTitles,
    (newTitles) => {
      bottomTitlesed.value = newTitles;
    },
    { deep: true }
  );

  watch(() => websocketStore.messages, (newMessages) => {
    if (websocketStore.lastMessage) {
      // const jsondata = JSON.parse(websocketStore.lastMessage.data)
    }
  },
    { deep: true }
  );
});

onBeforeUnmount(() => {
  // 修改：移除mitt事件监听
  // proxy.$mitt.off("updateBottomTitles");
  // proxy.$mitt.off("getCurrentBottomTitles");
  proxy.$mitt.off('checkedNodesChangedddd')
  // 清理绘图工具实例
  if (editpointTools.value) {
    editpointTools.value.destroy();
    editpointTools.value = null;
  }

  // 关闭所有弹窗
  dialogVisible.value = false;
  ismeteorology.value = false;
  isbattledensity.value = false;
  isfit.value = false;

  // 清理Cesium相关资源
  if (window.viewer && window.viewer.entities) {
    // 移除当前组件创建的实体（假设使用特定标签标识）
    window.viewer.entities.removeAll();
  }

  // 重置响应式数据
  tableData.value = [];
  proxy.$mitt.off("tude")
  proxy.$mitt.off("cesiumInitialized");
});

</script>

<style scoped>
/* 比例尺样式 */
.scale-bar {
  position: absolute;
  bottom: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  z-index: 999;
}

.scale-line {
  width: 100px;
  /* 线条长度 */
  height: 8px;
  /* 线条高度 */
  margin-right: 5px;
}

.scale-text {
  font-size: 12px;
  font-weight: bold;
}

.bottom_titlebiox {
  height: 32px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bottom_title {
  width: 600px;
  height: 50px;
  margin-left: 10px;
}

:deep(.el-select__placeholder) {
  color: #a8d6ff;
}

:deep(.el-form-item__label) {
  padding: 0;
  width: 70px;
}

:deep(.el-table th.el-table__cell) {
  background: #002245;
  /* border: none; */
  color: #1ffcda;
}

:deep(.el-table__empty-block) {
  background: #002245;
  border: none;
}

:deep(.el-table__row) {
  background: #002245;
}

:deep(.el-table) {
  --el-table-row-hover-bg-color: #023971;
  --el-table-current-row-bg-color: #03488d;
}

:deep(.el-table__body-wrapper) {
  background: #002245;
  color: #fff;
}

.dian {
  width: 4px;
  height: 4px;
  border: 1px solid #c7f5f5;
}

:deep(.el-select__wrapper) {
  background: #002245;
  height: 40px;
}

:deep(.el-input__wrapper) {
  background: #002245;
  height: 40px;
}

:deep(.el-input-number__increase) {
  height: 20px !important;
  line-height: 20px !important;
  background: #003367;
  color: #01c2ff;
}

:deep(.el-input-number__decrease) {
  height: 20px !important;
  line-height: 20px !important;
  background: #003367;
  color: #01c2ff;
}

.checkoutbox {
  height: 140px;
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.checkoutbox_item {
  width: 82px;
  height: 40px;
  background: #002245;
  border-radius: 4px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  cursor: pointer;
}

.checkoutbox_item:nth-child(5n) {
  margin-right: 0;
}

.btnstyle {
  width: 100px;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #0089ff;
  margin-right: 10px;
  background: transparent;
  font-size: 16px;
  color: rgba(1, 194, 255, 1);
}

.eldialog_cont {
  display: flex;
  margin-top: 20px;
  width: 100%;
  height: 802px;
  justify-content: space-between;
}

.eldialog_cont_left {
  width: 50%;
}

.eldialog_cont_right {
  width: 50%;
  height: 820px;
  margin: 0 -5px;
  background: #04335d;
}

.X_Plot_content {
  position: absolute;
  width: 100%;
  /* height: 150px; */
  bottom: 105px;
}

.X_Plot_bottom {
  position: absolute;
  width: 100%;
  /* height: 108px; */
  /* bottom: 0; */
  bottom: 5px;
  left: 0;
  /* background: yellow; */
}

.X_Plot_bottom_leftbtn {
  width: 780px;
  height: 70px;
  /* background: pink; */
  position: absolute;
  top: 30px;
  left: 600px;
  display: flex;
}

.X_Plot_bottom_leftbtn_item {
  /* width: 120px; */
  height: 47px;
  line-height: 47px;
  margin-left: 40px;
  margin-top: 10px;
  padding: 0 22px;
  text-align: center;
  background: #031d3b;
  border-radius: 4px;
}

.X_Plot_bottom_leftbtn_item_title {
  font-size: 18px;
  color: #fff700;
  /* line-height: 47px; */
  letter-spacing: 1px;
}

.btnactive {
  background: linear-gradient(360deg, #21a8ad 0%, rgba(31, 237, 210, 0) 100%);
  border-radius: 4px;
  border: 1px solid;
  border-image: linear-gradient(360deg,
      rgba(0, 255, 180, 1),
      rgba(253, 253, 253, 0)) 1 1;
}

/*  */

:deep(.el-tree) {
  background: none;
  color: #a8d6ff;
}

/* 鼠标浮动过的背景颜色 */
:deep(.el-tree-node__content:hover) {
  /* background: rgba(235, 243, 255, 0.10); */
  background: none;
}

:deep(.el-tree-node__content) {
  padding: 0 8px;
  height: 36px;
}

/* :deep(.el-tree-node__children) {
  margin: 20px 0;
} */

:deep(.el-text) {
  color: #a8d6ff;
}

/* 鼠标失去焦点时节点背景的颜色 */
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background: none;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: none;
}

/* 修改点击后的背景色为红色 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(235, 243, 255, 0.1) !important;
  border-radius: 4px;
}

/* 修改点击后的文字颜色（可选） */
/* :deep(.el-tree-node.is-current > .el-tree-node__content .el-tree-node__label) {
  color: white !important;
} */

/* :deep(.is-current) {
  color: red;
  background: red;
} */

:deep(.el-checkbox) {
  z-index: 0;
  margin-bottom: 0;
}


:deep(.el-pager li) {
  /* background: #003367; */
  background: none;
  color: #fff;
}

:deep(.el-pagination button:disabled) {
  /* background: #003367; */
  background: none;
  color: #fff;
}

.mbbh-dialog {
  position: relative;
  z-index: 1001;
}
</style>